import { db } from '../lib/db.js'
import type { Prisma } from '@prisma/client'

export class UserRepository {
  /**
   * 根据邮箱查找用户
   */
  async findByEmail(email: string) {
    return await db.user.findUnique({
      where: { email } as Prisma.UserWhereUniqueInput
    })
  }

  /**
   * 根据 UID 查找用户
   */
  async findByUid(uid: string) {
    return await db.user.findUnique({
      where: { uid }
    })
  }

  /**
   * 创建用户
   */
  async create(data: Prisma.UserCreateInput) {
    return await db.user.create({
      data
    })
  }

  /**
   * 更新用户
   */
  async update(uid: string, data: Prisma.UserUpdateInput) {
    return await db.user.update({
      where: { uid },
      data
    })
  }

  /**
   * 删除用户
   */
  async delete(uid: string) {
    return await db.user.delete({
      where: { uid }
    })
  }

  /**
   * 获取用户列表（支持分页和筛选）
   */
  async findMany(options: { limit?: number; offset?: number; where?: Prisma.UserWhereInput }) {
    const { limit = 10, offset = 0, where = {} } = options

    const [users, total] = await Promise.all([
      db.user.findMany({
        where,
        take: limit,
        skip: offset,
        orderBy: {
          createdAt: 'desc'
        }
        // 注意：不返回 password 字段，Prisma 会自动处理
      }),
      db.user.count({ where })
    ])

    return {
      users,
      total,
      limit,
      offset
    }
  }
}
